package com.kitwee.serialport.util;


public final class Bytes {

    private static final String HEXES = "0123456789ABCDEF";

    private Bytes() {
    }

    /**
     * 字节数组转十六进制字符串
     *
     * @param data 字节数组
     */
    public static String bytes2HexString(byte[] data) {
        if (data != null) {
            StringBuilder hex = new StringBuilder(2 * data.length);
            for (int i = 0; i <= data.length - 1; i++) {
                byte dataAtIndex = data[i];
                hex.append(HEXES.charAt((dataAtIndex & 0xF0) >> 4))
                        .append(HEXES.charAt((dataAtIndex & 0x0F)));
            }
            return hex.toString();
        } else {
            return null;
        }
    }

    /**
     * 十六进制字符串转字节数组
     *
     * @param hexString 十六进制字符串
     */
    public static byte[] hexString2Bytes(String hexString) {
        String stringProcessed = hexString.trim().replaceAll("0x", "");
        stringProcessed = stringProcessed.replaceAll("\\s+", "");
        byte[] data = new byte[stringProcessed.length() / 2];
        int i = 0;
        int j = 0;
        while (i <= stringProcessed.length() - 1) {
            byte character = (byte) Integer.parseInt(stringProcessed.substring(i, i + 2), 16);
            data[j] = character;
            j++;
            i += 2;
        }
        return data;
    }

    /**
     * 拼接byte数组
     *
     * @param arrays bytes数组
     */
    public static byte[] concatBytes(byte[]... arrays) {
        int length = 0;
        for (byte[] array : arrays) {
            length += array.length;
        }
        byte[] result = new byte[length];
        int pos = 0;
        for (byte[] array : arrays) {
            System.arraycopy(array, 0, result, pos, array.length);
            pos += array.length;
        }
        return result;
    }


}
